/**
 * 包含eaimonJYRHui的扩展和常用的方法
 * 
 * @author LiQianHui
 */

var imonJYRH = $.extend({}, imonJYRH);/* 全局对象 */

$.parser.auto = false;
$(function() {
	$.parser.parse(window.document);
	window.setTimeout(function() {
		$.messager.progress('close');
		if (self != parent) {
			window.setTimeout(function() {
				parent.$.messager.progress('close');
			}, 500);
		}
	}, 1);
	$.parser.auto = true;
});

$.fn.panel.defaults.onBeforeDestroy = function() {/* tab关闭时回收内存 */
	var frame = $('iframe', this);
	try {
		if (frame.length > 0) {
			frame[0].contentWindow.document.write('');
			frame[0].contentWindow.close();
			frame.remove();
			// if ($.browser.msie) {
			if(/msie/.test(navigator.userAgent.toLowerCase())){
				CollectGarbage();
			}
		} else {
			$(this).find('.combo-f').each(function() {
				var panel = $(this).data().combo.panel;
				panel.panel('destroy');
			});
		}
	} catch (e) {
	}
};

$.fn.dialog.defaults.onBeforeClose = function() {/* tab关闭时回收内存 */
	var frame = $('iframe', this);
	try {
		if (frame.length > 0) {
			frame[0].contentWindow.document.write('');
			if ($.browser.msie) {
				CollectGarbage();
			}
		} else {
			$(this).find('.combo-f').each(function() {
				var panel = $(this).data().combo.panel;
				panel.panel('destroy');
			});
		}
	} catch (e) {
	}
};

$.fn.panel.defaults.loadingMessage = '数据加载中，请稍候....';
$.fn.datagrid.defaults.loadMsg = '数据加载中，请稍候....';

var eaimonJYRHuiErrorFunction = function(XMLHttpRequest) {
	$.messager.progress('close');
	if(XMLHttpRequest.responseText.indexOf("#LOGIN#") == 0){
		$.messager.confirm(
			'提示',
			'确认:服务器超时，是否重新登陆！',
			function(r) {
				if (r) {
					if(window.parent!=window.self){
			    		window.parent.location.replace("${ctx}/!loginUI.do");
			    	}
				}
			});
	} else {
		$.messager.alert('错误', XMLHttpRequest.responseText.split('<script')[0]);
	}
};
$.fn.datagrid.defaults.onLoadError = eaimonJYRHuiErrorFunction;
$.fn.treegrid.defaults.onLoadError = eaimonJYRHuiErrorFunction;
$.fn.combogrid.defaults.onLoadError = eaimonJYRHuiErrorFunction;
$.fn.combobox.defaults.onLoadError = eaimonJYRHuiErrorFunction;
$.fn.form.defaults.onLoadError = eaimonJYRHuiErrorFunction;

$.fn.datagrid.defaults.onLoadSuccess = function(){
    $(this).datagrid('clearSelections'); // 一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
}

var eaimonJYRHuiPanelOnMove = function(left, top) {/* 防止超出浏览器边界 */
	if (left < 0) {
		$(this).window('move', {
			left : 1
		});
	}
	if (top < 0) {
		$(this).window('move', {
			top : 1
		});
	}
};
$.fn.panel.defaults.onMove = eaimonJYRHuiPanelOnMove;
$.fn.window.defaults.onMove = eaimonJYRHuiPanelOnMove;
$.fn.dialog.defaults.onMove = eaimonJYRHuiPanelOnMove;

$.extend($.fn.validatebox.defaults.rules, {
	eqPassword : {/* 扩展验证两次密码 */
		validator : function(value, param) {
			return value == $(param[0]).val();
		},
		message : '密码不一致！'
	},
	idcard : {/* 验证身份证 */
        validator : function(value) { 
            return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value); 
        }, 
        message : '身份证号码格式不正确' 
    },
    minLength: {
        validator: function(value, param){
            return value.length >= param[0];
        },
        message: '请输入至少（2）个字符.'
    },
    maxLength: {
        validator: function(value, param){
            return value.length <= param[0];
        },
        message: '请输入字符个数少于{0}.'
    },
    length:{validator:function(value,param){ 
        var len=$.trim(value).length; 
            return len>=param[0]&&len<=param[1]; 
        }, 
            message:"输入内容长度必须介于{0}和{1}之间." 
        }, 
    phone : {/* 验证电话号码 */ 
        validator : function(value) { 
            return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value); 
        }, 
        message : '格式不正确,请使用下面格式:020-88888888' 
    }, 
    mobile : {/* 验证手机号码 */ 
        validator : function(value) { 
            return /^(13|15|18)\d{9}$/i.test(value); 
        }, 
        message : '手机号码格式不正确' 
    }, 
    intOrFloat : {/* 验证整数或小数 */ 
        validator : function(value) { 
            return /^\d+(\.\d+)?$/i.test(value); 
        }, 
        message : '请输入数字，并确保格式正确' 
    }, 
    currency : {// 验证货币
        validator : function(value) { 
            return /^\d+(\.\d+)?$/i.test(value); 
        }, 
        message : '货币格式不正确' 
    }, 
    qq : {/* 验证QQ,从10000开始 */
        validator : function(value) { 
            return /^[1-9]\d{4,9}$/i.test(value); 
        }, 
        message : 'QQ号码格式不正确' 
    }, 
    integer : {/* 验证整数 */ 
        validator : function(value) { 
            return /^[+]?[1-9]+\d*$/i.test(value); 
        }, 
        message : '请输入整数' 
    }, 
    age : {/* 验证年龄 */
        validator : function(value) { 
            return /^(?:[1-9][0-9]?|1[01][0-9]|120)$/i.test(value); 
        }, 
        message : '年龄必须是0到120之间的整数' 
    }, 
    
    chinese : {/* 验证中文 */ 
        validator : function(value) { 
            return /^[\Α-\￥]+$/i.test(value); 
        }, 
        message : '请输入中文' 
    }, 
    english : {/* 验证英语 */ 
        validator : function(value) { 
            return /^[A-Za-z]+$/i.test(value); 
        }, 
        message : '请输入英文' 
    }, 
    unnormal : {/* 验证是否包含空格和非法字符 */ 
        validator : function(value) { 
            return /.+/i.test(value); 
        }, 
        message : '输入值不能为空和包含其他非法字符' 
    }, 
    username : {/* 验证用户名 */ 
        validator : function(value) { 
            return /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i.test(value); 
        }, 
        message : '用户名不合法（字母开头，允许6-16字节，允许字母数字下划线）' 
    }, 
    faxno : {/* 验证传真 */ 
        validator : function(value) { 
            return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value); 
        }, 
        message : '传真号码不正确' 
    }, 
    zip : {/* 验证邮政编码 */ 
        validator : function(value) { 
            return /^[1-9]\d{5}$/i.test(value); 
        }, 
        message : '邮政编码格式不正确' 
    }, 
    ip : {/* 验证IP地址 */ 
        validator : function(value) { 
            return /d+.d+.d+.d+/i.test(value); 
        }, 
        message : 'IP地址格式不正确' 
    }, 
    name : {/* 验证姓名，可以是中文或英文 */ 
            validator : function(value) { 
                return /^[\Α-\￥]+$/i.test(value)|/^\w+[\w\s]+\w+$/i.test(value); 
            }, 
            message : '请输入姓名' 
    },
    date : {/* 验证姓名，可以是中文或英文 */ 
        validator : function(value) { 
         // 格式yyyy-MM-dd或yyyy-M-d
            return /^(?:(?!0000)[0-9]{4}([-]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-]?)0?2\2(?:29))$/i.test(value); 
        },
        message : '清输入合适的日期格式'
    },
    msn:{ 
        validator : function(value){ 
        return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value); 
    }, 
    message : '请输入有效的msn账号(例：abc@hotnail(msn/live).com)' 
    },
    same:{ 
        validator : function(value, param){ 
            if($("#"+param[0]).val() != "" && value != ""){ 
                return $("#"+param[0]).val() == value; 
            }else{ 
                return true; 
            } 
        }, 
        message : '两次输入的密码不一致！'    
    } 
});

$.extend($.fn.datagrid.defaults.editors, {
	combocheckboxtree : {
		init : function(container, options) {
			var editor = $('<input/>').appendTo(container);
			options.multiple = true;
			editor.combotree(options);
			return editor;
		},
		destroy : function(target) {
			$(target).combotree('destroy');
		},
		getValue : function(target) {
			return $(target).combotree('getValues').join(',');
		},
		setValue : function(target, value) {
			$(target).combotree('setValues', imonJYRH.getList(value));
		},
		resize : function(target, width) {
			$(target).combotree('resize', width);
		}
	}
});
$.extend($.fn.datagrid.defaults.editors, {
	combogrid: {
		init: function(container, options){
			var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container); 
			input.combogrid(options);
			return input;
		},
		destroy: function(target){
			$(target).combogrid('destroy');
		},
		getValue: function(target){
			return $(target).combogrid('getValue');
		},
		setValue: function(target, value){
			$(target).combogrid('setValue', value);
		},
		resize: function(target, width){
			$(target).combogrid('resize',width);
		}
	}
});

/**
 * 获得项目根路径
 * 
 * 使用方法：imonJYRH.bp();
 */
imonJYRH.bp = function() {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	var localhostPaht = curWwwPath.substring(0, pos);
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	return (localhostPaht + projectName);
};

/**
 * 增加formatString功能
 * 
 * 使用方法：imonJYRH.fs('字符串{0}字符串{1}字符串','第一个变量','第二个变量');
 */
imonJYRH.fs = function(str) {
	for ( var i = 0; i < arguments.length - 1; i++) {
		str = str.replace("{" + i + "}", arguments[i + 1]);
	}
	return str;
};

/**
 * 增加命名空间功能
 * 
 * 使用方法：imonJYRH.ns('jQuery.bbb.ccc','jQuery.eee.fff');
 */
imonJYRH.ns = function() {
	var o = {}, d;
	for ( var i = 0; i < arguments.length; i++) {
		d = arguments[i].split(".");
		o = window[d[0]] = window[d[0]] || {};
		for ( var k = 0; k < d.slice(1).length; k++) {
			o = o[d[k + 1]] = o[d[k + 1]] || {};
		}
	}
	return o;
};

/**
 * 生成UUID
 */
imonJYRH.random4 = function() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
imonJYRH.UUID = function() {
	return (imonJYRH.random4() + imonJYRH.random4() + "-" + imonJYRH.random4() + "-" + imonJYRH.random4() + "-" + imonJYRH.random4() + "-" + imonJYRH.random4() + imonJYRH.random4() + imonJYRH.random4());
};

/**
 * 获得URL参数
 */
imonJYRH.getUrlParam = function(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null)
		return unescape(r[2]);
	return null;
};

imonJYRH.getList = function(value) {
	if (value) {
		var values = [];
		var t = value.split(',');
		for ( var i = 0; i < t.length; i++) {
			values.push('' + t[i]);/* 避免他将ID当成数字 */
		}
		return values;
	} else {
		return [];
	}
};

imonJYRH.png = function() {
	var imgArr = document.getElementsByTagName("IMG");
	for ( var i = 0; i < imgArr.length; i++) {
		if (imgArr[i].src.toLowerCase().lastIndexOf(".png") != -1) {
			imgArr[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgArr[i].src + "', sizingMethod='auto')";
			imgArr[i].src = "images/blank.gif";
		}
		if (imgArr[i].currentStyle.backgroundImage.lastIndexOf(".png") != -1) {
			var img = imgArr[i].currentStyle.backgroundImage.substring(5, imgArr[i].currentStyle.backgroundImage.length - 2);
			imgArr[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img + "', sizingMethod='crop')";
			imgArr[i].style.backgroundImage = "url('images/blank.gif')";
		}
	}
};
imonJYRH.bgPng = function(bgElements) {
	for ( var i = 0; i < bgElements.length; i++) {
		if (bgElements[i].currentStyle.backgroundImage.lastIndexOf(".png") != -1) {
			var img = bgElements[i].currentStyle.backgroundImage.substring(5, bgElements[i].currentStyle.backgroundImage.length - 2);
			bgElements[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img + "', sizingMethod='crop')";
			bgElements[i].style.backgroundImage = "url('images/blank.gif')";
		}
	}
};

imonJYRH.isLessThanIe8 = function() {/* 判断浏览器是否是IE并且版本小于8 */
	return ($.browser.msie && $.browser.version < 8);
};
imonJYRH.showZone=function(){
	$.messager.progress({
		text : '请求数据中....',
		interval : 100
	});
};
imonJYRH.hideZone=function(){
	$.messager.progress('close');
};
/** 处理URL缓存问题加了时间戳进去 */
imonJYRH.url= function(url) {
	if (url.indexOf("?") == -1) {
		url += "?timestamp=" + new Date().getTime();
	} else {
		url += "&timestamp=" + new Date().getTime();
	}
	return url;
}
/**
 * 对字符串操作，返回空串
 */
imonJYRH.fixup= function(src) {
	if(src==undefined||src==null){
		return "";
	}
	return src;
}
/**
 * 判断是否空对象
 */
imonJYRH.isBlank= function(src) {
	if(src==undefined||src==null){
		return true;
	}else if("string" == typeof src){
		if(""==src){
			return true;
		}
	}
	return false;
}
imonJYRH.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};
imonJYRH.getImageType = function(uri){
	if(uri==null||uri ==''||uri ==undefined){
		return '';
	}
	return uri.substring(uri.lastIndexOf("."));
};
imonJYRH.convertTree=function(rows){
	function exists(rows, parentId){
		for(var i=0; i<rows.length; i++){
			if (rows[i].id == parentId) return true;
		}
		return false;
	}
	var nodes = [];
	for(var i=0; i<rows.length; i++){
		var row = rows[i];
		if (!exists(rows, row.parentId)){
			nodes.push({
				id:row.id,
				text:row.text,
				iconCls:row.iconCls,
				attributes:row.attributes
			});
		}
	}
	var toDo = [];
	for(var i=0; i<nodes.length; i++){
		toDo.push(nodes[i]);
	}
	while(toDo.length){
		var node = toDo.shift();
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			if (row.parentId == node.id){
				var child = {id:row.id,text:row.text,iconCls:row.iconCls,attributes:row.attributes};
				if (node.children){
					node.children.push(child);
				} else {
					node.children = [child];
				}
				toDo.push(child);
			}
		}
	}
	return nodes;
};

/**
 * treeGrid初始化
 */
imonJYRH.convertTreeGrid=function(rows){
	function exists(rows, parentId){
		for(var i=0; i<rows.length; i++){
			if (rows[i].id == parentId) return true;
		}
		return false;
	}
	var nodes = [];
	for(var i=0; i<rows.length; i++){
		var row = rows[i];
		if (!exists(rows, row.parentId)){
			nodes.push({
				tsFunctionId:row.id,
				text:row.text,
				icon:row.icon,
				url:row.url,
				rowNo:row.rowNo,
				parentId:row.parentId,
				parentName:row.parentName
			});
		}
	}
	var toDo = [];
	for(var i=0; i<nodes.length; i++){
		toDo.push(nodes[i]);
	}
	while(toDo.length){
		var node = toDo.shift();
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			if (row.parentId == node.tsFunctionId){
				var child = {tsFunctionId:row.id,text:row.text,icon:row.icon,url:row.url,rowNo:row.rowNo,parentId:row.parentId,parentName:row.parentName};
				if (node.children){
					node.children.push(child);
				} else {
					node.children = [child];
				}
				toDo.push(child);
			}
		}
	}
	return nodes;
};
imonJYRH.NumberToFixed =function(value,length){
	if(null==value){
	  	return 0;
  	}
	if("number"== typeof value){
		var  result = new Number(value);
	  	return result.toFixed(length);
	}
	return 0;
};
imonJYRH.NumberToFixedThree =function(value){
	if(null==value){
	  	return 0;
  	}
	if("number"== typeof value){
		var  result = new Number(value);
	  	return result.toFixed(3);
	}
	return 0;
};
$.ajaxSetup({
	type : 'POST',
	timeout : 60*60*60*1000,
	data:'json',
	cache:false,
	error : function(XMLHttpRequest, textStatus, errorThrown) {/* 扩展AJAX出现错误的提示 */
		$.messager.progress('close');
		$.messager.alert('错误', XMLHttpRequest.responseText.split('<script')[0]);
	},
	complete:function(XMLHttpRequest,textStatus){
        var resText=XMLHttpRequest.responseText;
        try{
        	if(resText!=null&&resText!=""){
    	        if(resText.sessionState==0){ 
    	        	$.messager.confirm(
	        			'提示',
	        			'确认:服务器超时，是否重新登陆！',
	        			function(r) {
	        			if (r) {
	        				if(window.parent!=window.self){
	        			    	window.parent.location.replace("${ctx}/!loginUI.do");
	        			   }
	        			}
    	        	});
    	        }
            }
        }catch(e){
        	
        }
     }
});
